<template>
  <el-card class="box-card">
    <div class="header">
      <!-- 新建角色弹框 -->
      <el-button type="success" @click="handleAddRole" icon="el-icon-plus">新增角色</el-button>
    </div>
    <!-- 角色树表格开始 -->
    <div class="body">
      <el-table
        :data="roleList"
        style="width: 100%;margin-bottom: 20px;"
        row-key="roleId"
        border
        :tree-props="{children: '“children”', hasChildren: 'hasChildren'}"
        lazy
        :load="loadRole"
      >
        <el-table-column prop="roleId" label="角色编号" min-width="180" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" min-width="180" align="center"></el-table-column>
        <el-table-column prop="parentName" label="上级角色" min-width="180" align="center">
          <template slot-scope="{row}">
            <!-- <el-tag type="default">{{ row.parentName}}</el-tag> -->
            <el-tag v-if="row.parentId===0" type="default">{{ row.parentName}}</el-tag>
            <el-tag v-else type="success">{{ row.parentName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="310px"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="{row}">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showUpdateDialog(row.roleId)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(row.roleId)"
              plain
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 对话框模块 -->
    <el-dialog
      :visible.sync="dialogVisible"
      @close="dialogClose"
      :title="dialogType==='edit'?'编辑角色':'新建角色'"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="left">
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="角色标识" />
        </el-form-item>
        <!-- 上级角色 -->
        <el-form-item label="上级角色">
          <el-input type="text" v-model="form.parentName" :readonly="true" placeholder="请输入上级菜单">
            <el-button slot="append" @click="innerVisible = true">选择</el-button>
          </el-input>
        </el-form-item>
        <!-- <el-form-item>
          <template>
            <el-radio-group v-model="form.roleType">
              <el-radio :label="1">系统角色</el-radio>
              <el-radio :label="2">业务角色</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>-->
        <el-form-item>
          <template>
            <el-radio-group v-model="form.roleType">
              <el-radio
                v-for="(roletp,index) in roleTypeOptions"
                :label="roletp.value"
                :key="index"
              >{{roletp.name}}</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>

        <el-form-item label="菜单">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="deepTreelist"
            :props="treeProps"
            show-checkbox
            node-key="menuId"
            class="permission-tree"
            :default-checked-keys="selectedPermissionIds"
          />
        </el-form-item>

        <el-form-item label="说明">
          <el-input
            v-model="form.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>
      </el-form>
      <el-dialog width="30%" title="选择上级菜单" :visible.sync="innerVisible" append-to-body>
        <el-tree :data="CascaderData" :props="roleprops" @node-click="changeClick"></el-tree>
      </el-dialog>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import path from "path";
import { deepClone } from "@/utils";
import {
  tree,
  list,
  getRoleDetail,
  getRoutes,
  getRoles,
  addRole,
  deleteRole,
  updateRole,
} from "@/api/role";
// 引入部门列表方法
import { treeList } from "@/api/menu";
import { getData } from "@/api/dict";
let that;
export default {
  inject: ["reload"],
  filters: {
    queryRoleTypeFilter(key) {
      let typeName = "";
      console.log(that);
      that.positionTypeOptions.forEach((e) => {
        if (e.value === key) {
          typeName = e.name;
        }
      });
      return typeName;
    },
  },
  beforeCreate: function () {
    that = this;
  },
  data() {
    return {
      roleTypeOptions: [],
      selectedPermissionIds: [],
      // value: [],
      // roles: {},
      roleprops: { expandTrigger: "hover", label: "roleName", value: "roleId" },
      innerVisible: false,
      routes: [],
      // rolesList: [],
      // 判断对话框状态
      dialogVisible: false,
      dialogType: "new",
      // tree子父关联
      checkStrictly: false,
      // 树节点加载配置
      treeProps: {
        children: "children",
        label: "menuName",
        menuId: "menuId",
      },
      // 级联选择器数据绑定
      CascaderData: [],
      // 菜单tree数据绑定
      deepTreelist: [],
      form: {
        roleName: "",
        description: "",
        parentId: "",
        roleType: 1,
      },
      roleList: [],
      rules: {
        roleName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
    };
  },
  // 页面加载函数
  created() {
    this.roleTreeTable();
    this.getDictData();
  },
  methods: {
    getDictData() {
      const th = this;
      getData("roleType").then((res) => {
        th.roleTypeOptions = res.data;
      });
    },
    roleTreeTable() {
      tree().then((res) => {
        this.roleList = res.data;
        this.CascaderData = res.data;
      });
    },
    // 级联选择器数据绑定到form对象
    changeClick(obj, node, data) {
      this.form.parentId = obj.roleId;
      this.form.parentName = obj.roleName;
      this.innerVisible = false;
    },
    // tree表格加载
    loadRole(tree, treeNode, resolve) {
      list({ parentId: tree.roleId }).then((response) => {
        const data = response.data;
        resolve(data);
      });
    },
    // 触发点击新建时间
    handleAddRole() {
      // 对话框状态设置为添加
      this.dialogType === "new";
      // 是否显示对话框
      this.dialogVisible = true;
      // 是否显示复选框
      // this.checkStrictly = true;
      // 获取树形接口
      treeList().then((res) => {
        this.deepTreelist = res.data;
      });
    },
    showUpdateDialog(id) {
      // 加载角色
      let th = this;
      // 对话框状态设置为添加
      this.dialogType = "edit";
      // 是否显示对话框
      this.dialogVisible = true;
      let me = this;
      getRoleDetail(id).then((res) => {
        me.form = res.data;
        me.selectedPermissionIds = res.data.selectedPermissionIds;
        treeList().then((res) => {
          this.deepTreelist = res.data;
        });
      });
    },
    deleteRole(row) {
      this.$confirm("确认删除这个角色?", "Warning", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 输入确认删除选中
          deleteRole(row).then(() => {
            this.reload();
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //  保存事件
    confirmRole() {
      // 获取当前是添加还是编辑
      let th = this;
      let tatck = th.dialogType;
      // 表单数据是否合规
      th.$refs.form.validate((valid) => {
        if (valid) {
          // 判断是否为添加窗口
          if (tatck === "new") {
            th.form.permissionIds = this.$refs.tree.getCheckedKeys().join();
            addRole(th.form).then(() => {
              th.dialogVisible = false;
              this.reload();
            });
          } else {
            th.form.permissionIds = this.$refs.tree.getCheckedKeys().join();
            updateRole(th.form).then(() => {
              th.dialogVisible = false;
              this.reload();
            });
          }
        }
      });
    },
    // 对话框关闭时回调函数
    dialogClose() {
      this.$refs.form.resetFields();
      this.selectedPermissionIds = [];
      this.form.parentName = "";
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.box-card {
  height: 100%;
  margin: 10px 10px;
  padding: 0;
}
.permission-tree {
  margin-bottom: 30px;
}
</style>
